<template>
    <el-dialog
        v-model="dialogVisible"
        title="模板预览"
        width="60vw"
        top="20px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        class="new-template-dialog"
        @close="handleClose"
    >
      <div class="editor" v-if="formData.bjqlx === '01'">
        <RichTextEditor
            ref="richTextEditor"
            :value="formData.mbnr"
            @input="updateContent4"
            placeholder="请输入内容..."
            :toolbar-config="customToolbarConfig"
            @text-comment="handleTextComment"
            @variable-click="handleVariableClick"
            @blur="handleEditorBlur"
        />
      </div>
      <div class="editor" v-if="formData.bjqlx === '02'">
        <DocumentEditor
            id="previewEditor"
            ref="previewEditorRef"
            :documentServerUrl="documentServerUrl"
            :config="configEditor"
        />
      </div>
<!--        <template #footer>-->
<!--            <div class="dialog-footer">-->
<!--                <el-button @click="handleClose">取消</el-button>-->
<!--            </div>-->
<!--        </template>-->
    </el-dialog>
</template>

<script>
import { Close, Upload } from '@element-plus/icons-vue'
import RichTextEditor from '@/components/editor/index.vue'
import { DocumentEditor } from '@onlyoffice/document-editor-vue'
export default {
    name: 'NewTemplateDialog',
    components: {
        Close,
        Upload,
        RichTextEditor,
        DocumentEditor
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        formData: {
          type: Object,
          default: () => ({})
        }
    },
    emits: ['update:visible', 'confirm'],
    data() {
      const isProd = process.env.NODE_ENV === 'production'
      const apiUrl = isProd ? import.meta.env.VITE_ENV_API : import.meta.env.VITE_APP_BASE_API
        return {
          // 自定义工具栏配置
          customToolbarConfig: {
            show: true,
            groups: [
              {
                name: 'basic',
                title: '基础格式',
                tools: ['bold', 'italic','underline','strikethrough']
              },
              {
                name: 'align',
                title: '对齐方式',
                tools: ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull']
              },
              {
                name: 'insert',
                title: '插入',
                tools: ['insertIframe','insertVariable']
              },
              {
                name: 'action',
                title: '操作',
                tools: ['undo', 'redo', 'clear','comment','toggleComments']
              }
            ],
            fontSize: {
              show: true,
              options: [
                { value: '1', label: '12px' },
                { value: '2', label: '14px' },
                { value: '3', label: '16px' },
                { value: '4', label: '18px' },
                { value: '5', label: '20px' },
                { value: '6', label: '24px' },
                { value: '7', label: '36px' }
              ]
            },
            fontFamily: {
              show: true,
              options: [
                { value: '1', label: '微软雅黑' },
                { value: '2', label: '宋体' },
                { value: '3', label: '仿宋' },
                { value: '4', label: '楷体' },
                { value: '5', label: '黑体' }
              ]
            },
            colors: {
              show: true,
              textColor: true,
              backgroundColor: true
            },
          },
          documentServerUrl: import.meta.env.VITE_BASE_HTTP,
          configEditor: {},
          content4: '',
          apiUrl,
          userInfo: {},
        }
    },
    computed: {
        dialogVisible: {
            get() {
                return this.visible
            },
            set(value) {
                this.$emit('update:visible', value)
            }
        },
      constConfig () {
        return {
          documentType: "word",
          type: "desktop",
          document: {
            title: "",
            url: "",

            fileType: "docx", // 文件类型
            // onlyoffice用key做文件缓存索引，推荐每次都随机生成一下，不然总是读取缓存，后面应该是改成关联的文件的数据，例如表单的 id也是需要在后面添加个时间来避免缓存
            key: "",
          },
          editorConfig: {
            // 编辑器常规配置
            customization: {
              // 自动保存可以关闭，常规ctrl+s更好用
              //autosave: true,
              compactToolbar: false,
              forcesave: true,
              toolbarNoTabs: true,
              plugins: false,
              help: false,
              features: {
                // 关闭拼写检查
                spellcheck: false
              },
              compactHeader: true,
              hideRightMenu: true,
              toolbarHideFileName: true,
              logo: {
                image: "",
                url: ""
              },
              anonymous:{
                request:false
              }
            },
            mode: "view", // view为只能浏览  edit为编辑
            // 菜单显示语言
            lang: "zh-CN",
            user: {
              name: this.userInfo.xm,
              id: this.userInfo.yhm
            }
          }
        }
      }
    },
    watch: {
        visible(newVal) {
            if (newVal) {
                this.initFormData()
            }
        }
    },
  created(){
    this.userInfo = JSON.parse(localStorage.getItem('user'));
  },
    methods: {
      initFormData() {
        if (this.formData.bjqlx === '02'){
          this.getfiledata(this.formData)
        }
      },
        handleClose() {
            this.dialogVisible = false;
        },
      updateContent4(value) {
        // 只处理字符串类型的值，忽略事件对象
        if (typeof value === 'string') {
          this.content4 = value
        }
      },
      handleTextComment(data) {
        console.log('data',data);
      },
      // 处理变量点击事件（从富文本编辑器传来）
      handleVariableClick(variableId) {
        console.log('点击了变量:', variableId)
        this.highlightedVariableId = variableId

        // 找到对应的变量卡片并滚动到顶部
        this.$nextTick(() => {
          // 根据variableId找到对应的变量索引
          const variableIndex = this.variables.findIndex(v => v.id === variableId)
          if (variableIndex !== -1) {
            const variableCard = this.$refs[`variableCard_${variableIndex}`]
            if (variableCard && variableCard[0]) {
              const cardElement = variableCard[0]
              const configContent = this.$el.querySelector('.config-content')
              if (configContent) {
                // 计算卡片相对于配置内容的位置
                const cardRect = cardElement.getBoundingClientRect()
                const configRect = configContent.getBoundingClientRect()
                const scrollTop = cardElement.offsetTop - configContent.offsetTop - 20

                // 平滑滚动到变量卡片位置
                configContent.scrollTo({
                  top: Math.max(0, scrollTop),
                  behavior: 'smooth'
                })
              }
            }
          }
        })

        // 3秒后取消高亮
        setTimeout(() => {
          if (this.highlightedVariableId === variableId) {
            this.highlightedVariableId = null
          }
        }, 3000)
      },
      handleEditorBlur(data) {
        console.log('handleEditorBlur', data);

        // data 就是编辑器内容
        const editorContent = data;
        if (!editorContent) return;

        const foundVariables = [];

        // 只查找还没有被span包装的简单变量 {{变量名}}
        const simpleVariableRegex = /\{\{([^}]+)\}\}/g;

        let match;
        while ((match = simpleVariableRegex.exec(editorContent)) !== null) {
          // 检查这个变量是否已经被span包装
          const beforeMatch = editorContent.substring(0, match.index);
          const afterMatch = editorContent.substring(match.index + match[0].length);

          // 检查前面是否有未闭合的span标签
          const beforeSpans = (beforeMatch.match(/<span[^>]*>/g) || []).length;
          const beforeCloseSpans = (beforeMatch.match(/<\/span>/g) || []).length;
          const hasOpenSpan = beforeSpans > beforeCloseSpans;

          // 检查后面是否有span闭合标签
          const afterCloseSpans = (afterMatch.match(/<\/span>/g) || []).length;
          const afterSpans = (afterMatch.match(/<span[^>]*>/g) || []).length;
          const hasCloseSpan = afterCloseSpans > afterSpans;

          // 如果变量没有被span包装，则添加到处理列表
          if (!hasOpenSpan && !hasCloseSpan) {
            foundVariables.push({
              type: 'simple',
              fullMatch: match[0],
              variableName: match[1].trim(),
              startIndex: match.index,
              endIndex: match.index + match[0].length
            });
          }
        }

        // 去重（按变量名去重）
        const uniqueVariables = foundVariables.filter((variable, index, self) =>
            index === self.findIndex(v => v.variableName === variable.variableName)
        );

        console.log('找到的未包装变量:', uniqueVariables);
        console.log(this.$refs.richTextEditor.getVariables());

        // 只有当有未包装的变量时才处理内容
        if (uniqueVariables.length > 0) {
          let processedContent = editorContent;
          this.newVariablesArray = this.$refs.richTextEditor.getVariables();

          // 为简单变量添加span包装和id、class
          processedContent = processedContent.replace(/\{\{([^}]+)\}\}/g, (match, variableName) => {
            // 再次检查是否已经被span包装
            const beforeMatch = processedContent.substring(0, processedContent.indexOf(match));
            const afterMatch = processedContent.substring(processedContent.indexOf(match) + match.length);

            const beforeSpans = (beforeMatch.match(/<span[^>]*>/g) || []).length;
            const beforeCloseSpans = (beforeMatch.match(/<\/span>/g) || []).length;
            const hasOpenSpan = beforeSpans > beforeCloseSpans;

            const afterCloseSpans = (afterMatch.match(/<\/span>/g) || []).length;
            const afterSpans = (afterMatch.match(/<span[^>]*>/g) || []).length;
            const hasCloseSpan = afterCloseSpans > afterSpans;

            // 如果变量没有被span包装，则添加包装
            if (!hasOpenSpan && !hasCloseSpan) {
              const trimmedName = variableName.trim();
              const variableId = 'var_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
              const htmlContent = `<span id="${variableId}" class="editor-variable variable-element" data-variable-type="placeholder" data-variable-id="${variableId}">{{${trimmedName}}}</span>`;

              // 创建新的变量对象，延迟计算位置
              this.newVariable = {
                fullText: match,
                html: htmlContent,
                id: variableId,
                index: this.newVariablesArray.length,
                position: {
                  top: 0,
                  left: 0,
                  width: 0,
                  height: 0
                },
                text: trimmedName,
                bltext: trimmedName,
                variableType: "placeholder",
                endIndex: match.index + match.length,
                fullMatch: match,
                startIndex: match.index,
                type: "simple",
                variableName: trimmedName
              };

              this.newVariablesArray.push(this.newVariable);

              return htmlContent;
            }

            // 如果已经被包装，保持原样
            return match;
          });

          // 更新编辑器内容
          this.content4 = processedContent;

          // 将新创建的变量数组添加到现有的variables数组中
          this.variables = [...this.variables, ...this.newVariablesArray];

          // 延迟计算位置，确保DOM已更新
          this.$nextTick(() => {
            this.updateVariablePositions();
          });
          console.log('新创建的变量数组:', this.newVariablesArray);
          console.log('更新后的所有变量:', this.variables);
        }
        // 合并变量并去重
        const allVariables = [...this.$refs.richTextEditor.getVariables(), ...this.newVariablesArray];
        const uniqueVariables1 = [];
        const seenIds = new Set();

        allVariables.forEach(variable => {
          if (!seenIds.has(variable.id)) {
            seenIds.add(variable.id);
            uniqueVariables1.push(variable);
          }
        });

        this.variables = uniqueVariables1;
        console.log(this.variables);

        return uniqueVariables;
      },
      openInEditor(key,urlPrefix, fileType = 'docx') {
        this.configEditor = {
          ...this.constConfig,
          document: {
            ...this.constConfig.document,
            url: urlPrefix,
            fileType,
            key: key+"_"+this.userInfo.dwbm+"_"+this.userInfo.yhm+"_"+Date.now()
          },
        }
      },
      /* 获取文件数据并打开编辑器（示例） */
      getfiledata(data) {
        try {
          let url = ''
          let mbXxzjbh = ''
          if (this.formData.mode === 'add'){
            const clean = encodeURIComponent(data.fileName);
            url = `${this.apiUrl}/wsmbgl/filedown?fileName=${clean}`
            mbXxzjbh = data.xxzjbh
          }else if (this.formData.mode === 'edit'){
            url = `${this.apiUrl}/wsmbgl/getMbWsnr?xxzjbh=${data.xxzjbh}`
            mbXxzjbh = data.xxzjbh
          }
          this.openInEditor(mbXxzjbh,url, '');
        } catch (e) {
          console.error(e);
        }
      },
    }
}
</script>

<style scoped>
/* 新建模板弹窗样式 */
:deep(.new-template-dialog .el-dialog__header) {
    padding: 20px 20px 10px 20px;
    border-bottom: 1px solid #e4e7ed;
}

:deep(.new-template-dialog .el-dialog__title) {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

:deep(.new-template-dialog .el-dialog__body) {
    padding: 20px;
    height: 50vh;
}

:deep(.new-template-dialog .el-dialog__footer) {
    padding: 10px 20px 20px 20px;
    border-top: 1px solid #e4e7ed;
}


.editor {
  background: white;
  border-radius: 0.417vw;
  box-shadow: 0 0.104vw 0.625vw 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  /* overflow: hidden; */
  transition: width 0.3s ease;
  height: 80vh;
}

.editor :deep(.rich-text-editor) {
  height: 100%;
  flex: 1;
}
.mode-selection {
    margin-bottom: 20px;
}

.mbflmc-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 6px;
}
.mbflmc-label {
  color: #888;
  font-size: 14px;
}
.mbflmc-value {
  color: #2567E9;
  font-size: 15px;
  font-weight: 500;
}

.mode-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
}

.mode-buttons {
    display: flex;
    gap: 20px;
}

.mode-button {
    flex: 1;
    height: 120px;
    border: 2px solid #e4e7ed;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #fafafa;
}

.mode-button:hover {
    border-color: #2567E9;
    background: #f0f8ff;
}

.mode-button.active {
    border-color: #2567E9;
    background: #f0f8ff;
}

.mode-icon {
    font-size: 32px;
    font-weight: bold;
    color: #2567E9;
    margin-bottom: 10px;
}

.mode-text {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.file-display {
    margin-top: 15px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
}

.file-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.file-icon {
    font-size: 20px;
    color: #2567E9;
}

.file-name {
    flex: 1;
    font-size: 14px;
    color: #333;
}

.file-remove {
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    color: #999;
    transition: all 0.2s ease;
}

.file-remove:hover {
    background: #f0f0f0;
    color: #f56c6c;
}

.upload-area {
    margin-top: 15px;
}

.upload-content {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    padding: 40px 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.upload-content:hover {
    border-color: #2567E9;
    background: #f0f8ff;
}

.upload-icon {
    font-size: 32px;
    color: #999;
    margin-bottom: 10px;
}

.upload-text {
    font-size: 14px;
    color: #666;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.new-template-dialog .el-button) {
    padding: 8px 20px;
    font-size: 14px;
}

:deep(.new-template-dialog .el-button--primary) {
    background: #2567E9;
    border-color: #2567E9;
}

:deep(.new-template-dialog .el-button--primary:hover) {
    background: #1e5fd9;
    border-color: #1e5fd9;
}
</style>
